package edu.rutgers.moko;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;

import edu.rutgers.moko.data.MyTask;
import edu.rutgers.moko.data.util.FieldAccessUtil;

/**
 * 
 * @author Darja Krushevskaja
 * 
 */
public class RssServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final String DEFAULT_FEED_TYPE = "default.feed.type";
	private static final String FEED_TYPE = "type";
	private static final String MIME_TYPE = "application/xml; charset=UTF-8";
	private static final String COULD_NOT_GENERATE_FEED_ERROR = "Could not generate feed";
	private String _defaultFeedType;
	private MyTask task;
	//private final File dir = new File("/home/dashali/Documents/school/projects/server");
	private final File dir = new File("/home/root/server");
	private final File msgs = new File(dir, "properties.txt");

	
	public RssServlet(MyTask task) {
		this.task = task;
	}

	public void init() {
		_defaultFeedType = getServletConfig().getInitParameter(DEFAULT_FEED_TYPE);
		_defaultFeedType = (_defaultFeedType != null) ? _defaultFeedType: "atom_0.3";
	}

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		try {
			SyndFeed feed = getFeed(req);

			String feedType = req.getParameter(FEED_TYPE);
			feedType = (feedType != null) ? feedType : _defaultFeedType;
			feed.setFeedType(feedType);

			res.setContentType(MIME_TYPE);
			SyndFeedOutput output = new SyndFeedOutput();
			output.output(feed, res.getWriter());
		} catch (FeedException ex) {
			String msg = COULD_NOT_GENERATE_FEED_ERROR;
			log(msg, ex);
			res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
		}
	}

	@SuppressWarnings("unchecked")
	protected SyndFeed getFeed(HttpServletRequest req) throws IOException,
			FeedException {
		SyndFeed feed = new SyndFeedImpl();
		List<String> lines = new ArrayList<String>();
		if (msgs.exists()) {
			lines = FileUtils.readLines(msgs);
		}
		FieldAccessUtil faUtil = new FieldAccessUtil(lines);


		feed.setTitle("OM>> Feed Page ");
		feed.setLink("/rss");
		feed.setDescription("This feed contains information about openmoko");
		feed.setEntries(task.getFeeds(req.getRemoteAddr(), faUtil));
		return feed;
	}

}
